package com.elinkway.infinitemovies.utils;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.UpgradeInfoParser;
import com.elinkway.infinitemovies.service.UpdateService;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;

public class UpdateManager {

    private static final int LOGIN = 0;
    private static final int DOWN_ERROR = 1;
    public static final int CHECK_ERROR = 2;
    public static final int STORE_ERROR = 3;
    public static final int FINISH = 4;
    protected static final int CANCEL_DOWNLOAD = 5;
    private static boolean isUpdating = false;
    private Context mContext;
    private RequestUpdateInfo requestTask;
    private UpgradeInfo info;
    private UpdateListener mUpdateListener;

    private Handler mMainHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_ERROR:
                    showFailedDialog("失败", "升级出错，请稍后重试！");
                    break;
                case LOGIN:
                    break;
                case CHECK_ERROR:
                    if (mUpdateListener != null) {
                        mUpdateListener.onCheckError();
                    } else {
                        UIs.showToast(R.string.check_new_failed);
                    }
                    break;
                case FINISH:
                    break;
            }
        }

    };

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    public static void setUpdating(boolean isUpdating) {
        UpdateManager.isUpdating = isUpdating;
    }

    public void setmUpdateListener(UpdateListener mUpdateListener) {
        this.mUpdateListener = mUpdateListener;
    }

    public void startCheck() {
        if (isUpdating) {
            return;
        }
        isUpdating = true;
        if (requestTask != null) {
            requestTask.cancel();
        }
        requestTask = new RequestUpdateInfo(MoviesApplication.getInstance());
        requestTask.start();
    }

    private class RequestUpdateInfo extends MoviesHttpAsyncTask<UpgradeInfo> {


        @Override
        public void netNull() {
            isUpdating = false;
            Message msg = new Message();
            msg.what = CHECK_ERROR;
            mMainHandler.sendMessage(msg);
            super.netNull();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            isUpdating = false;
            Message msg = new Message();
            msg.what = CHECK_ERROR;
            mMainHandler.sendMessage(msg);
            super.netErr(updateId, errMsg);
        }

        public RequestUpdateInfo(Context context) {
            super(context);
        }

        @Override
        public LVideoDataHull<UpgradeInfo> doInBackground() {
            return MoviesHttpApi.requestUpgrade(new UpgradeInfoParser());
        }

        @Override
        public void onPostExecute(int updateId, UpgradeInfo result) {
            info = result;
            if (!TextUtils.isEmpty(result.getVersion()) && VersionUtil.compare(result.getVersion(), MoviesUtils.getClientVersionName()) > 0) {
                if (!result.isUpgrade()) {
                    isUpdating = false;
                    if (mUpdateListener == null) {
                        showDontNeedUpdateDialog(result);
                    } else {
                        mUpdateListener.onComplete();
                    }
                } else if ("suggest".equals(result.getType())) {
                    showSuggestDialog(result);
                } else if ("force".equals(result.getType())) {
                    showForceDialog(result);
                } else {
                    if (null != mUpdateListener) {
                        mUpdateListener.onComplete();
                    }
                }
            } else {
                isUpdating = false;
                if (mUpdateListener == null) {
                    showDontNeedUpdateDialog(result);
                } else {
                    mUpdateListener.onComplete();
                }
            }
        }

    }

    private void showSuggestDialog(final UpgradeInfo updateInfo) {
        AlertDialog.Builder builder = new Builder(mContext);
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        View customView = layoutInflater.inflate(R.layout.dialog_alert_update, null);
        builder.setView(customView);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();

        TextView title = (TextView) customView.findViewById(R.id.title);
        TextView msg = (TextView) customView.findViewById(R.id.msg);
        Button okBtn = (Button) customView.findViewById(R.id.btn_ok);
        Button cancelBtn = (Button) customView.findViewById(R.id.btn_cancel);
        msg.setText(updateInfo.getDesc());
        title.setText(String.format("检测到新版本v%s", updateInfo.getVersion()));
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                if (mUpdateListener != null) {
                    mUpdateListener.onComplete();
                }
                startDownload();
            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isUpdating = false;
                alertDialog.dismiss();
                if (mUpdateListener != null) {
                    mUpdateListener.onCancel();
                }
            }
        });
    }

    public void showDontNeedUpdateDialog(UpgradeInfo result) {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setMessage("已经是最新版！");
        builder.setTitle("提示");
        builder.setPositiveButton("确定", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (mUpdateListener != null) {
                    mUpdateListener.onComplete();
                }
            }
        });
        builder.setCancelable(true);
        builder.create().show();
    }

    private void showForceDialog(final UpgradeInfo updateInfo) {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setMessage(String.format("当前版本过低，为保证使用，请立即升级至v%s", updateInfo.getVersion()));
        builder.setTitle("提示");
        builder.setPositiveButton("升级", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startDownload();
            }
        });

        builder.setNegativeButton("退出", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                isUpdating = false;
                dialog.dismiss();
                if (mUpdateListener != null) {
                    mUpdateListener.onFinish();
                }
            }

        });
        builder.setCancelable(false);
        builder.create().show();
    }

    private void showFailedDialog(String title, String content) {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setMessage(content);
        builder.setTitle(title);
        builder.setPositiveButton("重试", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (info != null) {
                    startDownload();
                } else {
                    new RequestUpdateInfo(mContext).start();
                }
            }

        });

        builder.setNegativeButton("取消", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (info.getType().equals("force")) {
                    Message msg = new Message();
                    if (mUpdateListener != null) {
                        mUpdateListener.onFinish();
                    }
                } else if (info.getType().equals("suggest")) {
                    Message msg = new Message();
                    if (mUpdateListener != null) {
                        mUpdateListener.onCancel();
                    }
                } else {
                    if (mUpdateListener != null) {
                        mUpdateListener.onComplete();
                    }
                }
            }

        });
        builder.setCancelable(false);
        builder.create().show();
    }

    /**
     * 升级正版的对话框
     *
     * @author daipei
     */
    @SuppressLint("NewApi")
    public void showOriginalDialog() {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setMessage(mContext.getString(R.string.update_tips_app_office_error));
        builder.setTitle("提示");
        builder.setPositiveButton("下载原版", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                piracyUpdate();
                dialog.dismiss();
            }

        });

        builder.setNegativeButton("退出", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }

        });
        builder.setCancelable(true);
        builder.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                MoviesApplication.getInstance().exitApplication(true);
            }

        });
        builder.create().show();
    }

    public interface UpdateListener {

        void onCancel();

        void onFinish();

        void onCheckError();

        void onComplete();
    }

    private void startDownload() {
        Intent updateIntent = new Intent(mContext, UpdateService.class);
        updateIntent.putExtra("url", info.getLink());
        mContext.startService(updateIntent);
    }

    public static boolean isUpdating() {
        return isUpdating;
    }

    /**
     * 盗版强制升级策略
     * 优先吊起android商店
     * 其次进入浏览器下载页
     */
    private void piracyUpdate() {
        try {
            //吊起android商店
            Uri uri = Uri.parse("market://details?id=" + mContext.getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            //进入浏览器下载页
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse("http://api1.le123.com/yingshidaquan/download/");
            intent.setData(content_url);
            mContext.startActivity(intent);
        }
    }

}
